package com.xb.loan.util.binaryConvert;


import java.io.UnsupportedEncodingException;

/**
 * 
 * 加密解密
 */
public class CryptUtil {

	private static final int KEYLEN = 5;

	private static final byte[] KEYVAL = { 0x04, 0x08, 0x04, 0x08, 0x10 };

	/**
	 * 
	 * @param data ――存放整个消息包的的字符
	 * @param result ――指向加密后的消息包
	 * @param inlen ――整个消息包长度
	 * @return 函数返回值为加密后的消息包长度，如果加密正确，该数值为inlen + 1
	 */
	public static int encode(byte[] data, byte[] result, int inlen) {

		byte f = 0;
		int i, j;

		for (i = 0; i < inlen; i++) {

			if (i == 0) {

				f = data[i];
			} else {

				f = (byte) (f ^ (data[i]));
			}

			j = i % KEYLEN;

			if ((data[i] & KEYVAL[j]) != 0) {

				result[i] = (byte) (data[i] & (~KEYVAL[j]));
			} else {

				result[i] = (byte) (data[i] | KEYVAL[j]);
			}

		}

		result[inlen] = f;

		return (inlen + 1);
	}

	/**
	 * 
	 * @param data  ――指向接收到的加密后的消息
	 * @param result ――存放解密后的整个消息包的的字符
	 * @param inlen ――整个消息包长度
	 * @return 返回值为解密后的消息包长度，如果解密正确，该数值为inlen - 1
	 */
	public static int decode(byte[] data, byte[] result, int inlen) {

		byte f = 0;
		int i, j;

		for (i = 0; i < inlen - 1; i++) {

			j = i % KEYLEN;

			if ((data[i] & KEYVAL[j]) != 0) {

				result[i] = (byte) (data[i] & (~KEYVAL[j]));
			} else {

				result[i] = (byte) (data[i] | KEYVAL[j]);
			}

			if (i == 0) {

				f = result[i];
			} else {

				f = (byte) (f ^ (result[i]));
			}

		}

		if (data[i] == f) {

			return (inlen - 1);
		} else {

			return (-1);
		}
	}

	public static void main(String[] args) throws UnsupportedEncodingException {

		String ss = "test中文332";

		byte[] r = ss.getBytes("gbk");

		byte[] res = new byte[r.length + 1];
		
		int i1 = encode(r, res, r.length);

		System.out.println(i1);

		byte[] r2 = new byte[res.length - 1];
		
		int i2 = decode(res, r2, res.length);
		
		System.out.println(new String(r2,"gbk"));
		
		System.out.println(i2);
		
	}

}
